import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    TouchableHighlight,
    SectionList,
    TouchableOpacity,
    TextInput, DeviceEventEmitter,
    Modal
} from 'react-native';
import Swiper from 'react-native-swiper';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import AsyncStorage from '@react-native-community/async-storage';
import styles from './styles';
import app from '../../../app.json';
import Ugame from '../../../Ugame';
import CommonDialog from 'react-native-dialogs-master';
import Httpc from '../../utils/Httpc';
import REQUEST from '../../../REQUEST';


import JPush from 'jpush-react-native';
const { width, height } = Dimensions.get('window');
// 初始化总数据

export default class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            refreshing: false,
            name: '小店',
            phone: '',
            passcode: '',

            type: 1,//1，验证码登录，2密码登录
            device: 0,//0未知设备，1安卓设备，2ios设备登录

            isshow: true,
            isclear: false,

            timerCount: 60,
            timerTitle: '获取验证码',
            counting: false,

            toastModelVisible: false,
            message: 'message',
            deviceID: null,
        };
        this.isloging = false;

    }
    //Platform.OS === 'android'
    static navigationOptions = {
        title: '',
        //header: null,  //隐藏顶部导航栏
        //tabBarVisible: false, // 隐藏底部导航栏
        headerStyle: {
            backgroundColor: 'transparent',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
            fontWeight: 'bold',
        },
    }
    componentDidMount() {
        let os = 0;
        if (Platform.OS == 'android') {
            os = 1;
        }
        if (Platform.OS == 'ios') {
            os = 2;
        }
        this.setState({
            device: os
        });
        JPush.getRegistrationID((result) => {
            this.setState({
                deviceID:result.registerID
            });
            }
        )

    }

    onPhoneChangeText(phone) {
        this.setState({
            phone: phone,
            isshow: phone.length == 11 ? true : false,
            isclear: phone.length > 0 ? true : false,
        })
    }
    _do_clear_phone() {
        this.setState({
            phone: null,
            isshow: false,
            isclear: false,
        })
    }
    _do_getCode() {
        if (this.state.counting) {
            return;
        }
        if (!(/^1[3456789]\d{9}$/.test(this.state.phone))) {
            this.do_toast('手机号码格式错误', 500);
            return false;
        }
        Httpc.get(REQUEST.send_code, { phone: this.state.phone, ishave: 0 }, function (res) {
            this.do_toast(res.Message, 500);
            if (res.StatusCode != 1) {
                return;
            }
            this._do_set_timer();
        }.bind(this));

    }
    //倒计时
    _do_set_timer() {
        this.setState({
            counting: true
        });
        let timerCount = this.state.timerCount;
        this._timer = setInterval(() => {
            timerCount--;
            if (timerCount > 0) {
                this.setState({
                    timerTitle: '剩余' + timerCount + 's'
                });
            } else {
                clearInterval(this._timer);
                this.setState({
                    timerCount: 60,
                    counting: false,
                    timerTitle: '获取验证码',
                });
            }
        }, 1000);
    }
    do_login() {
        if (this.isloging) {
            return;
        }
        this.isloging = true;
        clearInterval(this._timer);

        if (!(/^1[3456789]\d{9}$/.test(this.state.phone))) {
            this.isloging = false;
            this.do_toast("手机号码格式错误", 500);
            return false;
        }
        if (this.state.passcode.length == 0) {
            this.isloging = false;
            if (this.state.type == 1) {
                this.do_toast("验证码格式错误", 500);
            } else {
                this.do_toast("请输入密码", 500);
            }
            return false;
        }
        let params = {};
        params.phone = this.state.phone;
        params.passcode = this.state.passcode;
        params.rootid = app.rootid;//渠道id
        params.type = this.state.type; //1验证码登陆 2密码登陆
        params.device = this.state.device; //0.未知 1.android 2.ios
        params.deviceID=this.state.deviceID;
        const navigation = this.props.navigation;
        Httpc.postJson(REQUEST.login, params, function (res) {
            this.isloging = false;
            console.log(res);
            if (res.StatusCode != 1) {
                this.do_toast(res.Message, 1000);
                return;
            }
            Ugame.setUserData(res.Data, function () {
                // 在登录页面,在goBack之前,将上个页面的方法取到,并回传参数,这样回传的参数会重走render方法
                DeviceEventEmitter.emit('updateLogin', {});
                navigation.goBack();
            });
        }.bind(this));

    }
    showPhoneSubmit() {
        return (
            <View>
                <View style={[styles.input, styles.line]}>
                    <Image resizeMode="cover" style={{ width: 17, height: 20 }} source={require('../../image/js_img_ic_input_password.png')} />
                    <TextInput
                        style={{ width: width - 140, height: 40, marginLeft: 11 }}
                        placeholder="验证码"
                        placeholderTextColor="#CCC"
                        keyboardType='numeric'
                        onChangeText={(passcode) => this.setState({ passcode })}
                    // onEndEditing={this.dissmissKeyboard.bind(this)}
                    />
                    <TouchableOpacity onPress={() => this._do_getCode()}>
                        <Text style={this.state.counting ? styles.yes_disabled : styles.no_disabled}>{this.state.timerTitle}</Text>
                    </TouchableOpacity>
                </View>
                <TouchableOpacity onPress={() => this.do_login()}>
                    <View style={styles.login_btn}>
                        <Text style={{ color: '#ffffff', fontSize: 16 }}>登录</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
    showPassSubmit() {
        return (
            <View>
                <View style={[styles.input, styles.line]}>
                    <Image resizeMode="cover" style={{ width: 17, height: 20 }} source={require('../../image/js_img_ic_input_password.png')} />
                    <TextInput
                        style={{ width: width - 140, height: 40, marginLeft: 11 }}
                        placeholder="请输入密码"
                        placeholderTextColor="#CCC"
                        keyboardType='numeric'
                        onChangeText={(passcode) => this.setState({ passcode })}
                    // onEndEditing={this.dissmissKeyboard.bind(this)}
                    />
                </View>
                <TouchableOpacity onPress={() => this.do_login()}>
                    <View style={styles.login_btn}>
                        <Text style={{ color: '#ffffff', fontSize: 16 }}>登录</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
    showClear() {
        return (
            <View>
                <TouchableOpacity onPress={() => this._do_clear_phone()}>
                    <Image resizeMode="cover" style={{ width: 16, height: 16 }} source={require('../../image/js_img_ic_order_delete.png')} />
                </TouchableOpacity>
            </View>
        );
    }

    render_pass_login = () => {
        return (
            <View style={[styles.input, styles.line]}>
                <Image resizeMode="cover" style={{ width: 13, height: 19 }} source={require('../../image/js_img_ic_input_phone.png')} />
                <TextInput
                    style={{ width: width - 85, height: 40, marginLeft: 15 }}
                    placeholder="手机号"
                    placeholderTextColor="#CCC"
                    keyboardType='numeric'
                    onChangeText={(phone) => this.onPhoneChangeText(phone)}
                    maxLength={11}
                    value={this.state.phone}
                />
            </View>
        );

    }
    _do_change_type = () => {
        let type = this.state.type;
        if (type == 1) {
            this.setState({
                type: 2
            });
        } else {
            this.setState({
                type: 1
            });
        }
    }
    do_toast = (str, time) => {
        this.setState({
            message: str,
            toastModelVisible: true
        });
        setTimeout(() => {
            this.setState({
                message: '',
                toastModelVisible: false
            });
        }, time);
    }
    toast = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={this.state.toastModelVisible}
                onRequestClose={() => {
                    this.setState({
                        toastModelVisible: false
                    });
                }}
            >
                <View style={{ flexDirection: 'row', justifyContent: 'center', position: 'absolute', bottom: 100, width: width }}>
                    <Text style={{ backgroundColor: 'rgba(0,0,0,0.5)', color: '#ffffff', borderRadius: 10, height: 40, lineHeight: 40, paddingLeft: 20, paddingRight: 20 }}>{this.state.message}</Text>
                </View>
            </Modal>
        );
    }
    render() {
        let name = this.state.name;
        let isshow = this.state.isshow;
        let isclear = this.state.isclear;
        let type = this.state.type;
        return (
            <View style={styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                <ScrollView>
                    <View style={styles.header}>
                        <Text style={{ fontSize: 24, color: '#ffffff' }}>欢迎加入{name}</Text>
                        <Text style={{ fontSize: 14, color: '#ffffff' }}>请输入手机号登录店铺</Text>
                    </View>
                    <View style={styles.inputContent}>
                        <View style={[styles.input, styles.line]}>
                            <Image resizeMode="cover" style={{ width: 13, height: 19 }} source={require('../../image/js_img_ic_input_phone.png')} />
                            <TextInput
                                style={{ width: width - 85, height: 40, marginLeft: 15 }}
                                placeholder="手机号"
                                placeholderTextColor="#CCC"
                                keyboardType='numeric'
                                onChangeText={(phone) => this.onPhoneChangeText(phone)}
                                maxLength={11}
                                value={this.state.phone}
                            />
                            {isclear ? this.showClear() : null}
                        </View>
                        {type == 1 ? this.showPhoneSubmit() : this.showPassSubmit()}
                        <TouchableOpacity style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', margin: 10 }} onPress={() => this._do_change_type()}>
                            {type == 1 ? <Text style={{ color: '#666666' }}>帐号密码登录</Text> : <Text style={{ color: '#666666' }}>短信快捷登录</Text>}
                        </TouchableOpacity>
                    </View>
                </ScrollView>
                {this.toast()}
            </View>
        );
    }
}
